package com.joekai.view_demo.kugou_sideslip;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.RelativeLayout;

import androidx.core.view.ViewCompat;

import com.joekai.view_demo.R;
import com.joekai.view_demo.utils.PxUtils;

public class SideslipLayout extends HorizontalScrollView {
    private View mMenuView, mContentView, mShadowView;
    // 系统自带的手势处理类
    private GestureDetector mGestureDetector;
    private boolean mIsOpenMenu = false;
    private int mMenuWidth;
    private boolean mIsIntercept = false;

    private boolean mContentViewZoom = true;

    private boolean mIsAddShadowView = true;

    public SideslipLayout(Context context) {
        this(context,null);
    }

    public SideslipLayout(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public SideslipLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr,0);
    }

    public SideslipLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        mGestureDetector = new GestureDetector(context, new GestureDetectorListener());

        // 初始化自定义属性
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.SideSlipLayout);

        mMenuWidth = (int) array.getDimension(
                R.styleable.SideSlipLayout_menuWidth, PxUtils.dp2px(50));

//        mMenuWidth = (int) (PxUtils.getScreenWidth()
//                - rightMargin);

        array.recycle();
    }

    public synchronized boolean getIsOpenMenu() {
        return mIsOpenMenu;
    }

    /**
     * 这个方法代表整个布局加载完毕
     */
    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        //获取子view 相当于LinearLayout
        ViewGroup viewGroup = (ViewGroup) getChildAt(0);

        int childCount = viewGroup.getChildCount();
        //只能有两个子view
        if (childCount != 2) {
            throw new RuntimeException("只能放置两个子View");
        }

        //菜单页的宽度 是 屏幕的宽度减右边一部分的距离
        mMenuView = viewGroup.getChildAt(0);
        ViewGroup.LayoutParams menuParams = mMenuView.getLayoutParams();
        menuParams.width = mMenuWidth;
        //7.0以下手机 必须添加这句
        mMenuView.setLayoutParams(menuParams);

        //内容页的宽度 屏幕的宽度
        mContentView = viewGroup.getChildAt(1);
        if (mIsAddShadowView) {
            ViewGroup.LayoutParams contentParams = mContentView.getLayoutParams();
            //先将View移除
            viewGroup.removeView(mContentView);
            //为添加阴影
            RelativeLayout contentLayout = new RelativeLayout(getContext());
            //将内容布局加入
            contentLayout.addView(mContentView);
            mShadowView = new View(getContext());
            mShadowView.setBackgroundColor(0x77000000);
            contentLayout.addView(mShadowView);
            // 最后在把容器放回原来的位置
            contentParams.width = PxUtils.getScreenWidth();
            contentLayout.setLayoutParams(contentParams);
            viewGroup.addView(contentLayout);
            mShadowView.setAlpha(0.0f);
        } else {
            ViewGroup.LayoutParams contentParams = mContentView.getLayoutParams();
            contentParams.width = PxUtils.getScreenWidth();
            mContentView.setLayoutParams(contentParams);
        }

    }


    /**
     * 事件拦截
     *
     * @param ev
     * @return
     */
    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        mIsIntercept = false;
        if (mIsOpenMenu) {
            float currentX = ev.getX();
            if (currentX > mMenuWidth) {
                //关闭菜单
                closeMenu();
                //子View不需要响应任何事件（点击和触摸），拦截子View的事件
                //如果返回true，代表会拦截子View的事件，但是会响应自己的onTouch事件
                mIsIntercept = true;
                return true;
            }
        }
        return super.onInterceptTouchEvent(ev);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        scrollTo(mMenuWidth, 0);
    }
    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
        // 1.内容动画   只有一个缩放   1.0f - 0.7
        // 计算梯度值
        float scale = l * 1f / mMenuWidth;// scale 1f-0.0f

        float rightScale = 0.7f + 0.3f * scale;// 1.0 - 0.7
        // 设置缩放的中心点  兼容低版本动画 需要下一个动画的兼容包 nineoldandroid
        // Compat 大部分是兼容   LayoutInflaterCompat( 插件式换肤也是为了兼容 )
        if (mContentViewZoom) {
            ViewCompat.setPivotX(mContentView, 0);
            ViewCompat.setPivotY(mContentView, mContentView.getHeight() / 2);
            ViewCompat.setScaleX(mContentView, rightScale);
            ViewCompat.setScaleY(mContentView, rightScale);
            if (mIsAddShadowView) {

                ViewCompat.setPivotX(mShadowView, 0);
                ViewCompat.setPivotY(mShadowView, mShadowView.getHeight() / 2);
                ViewCompat.setScaleX(mShadowView, rightScale);
                ViewCompat.setScaleY(mShadowView, rightScale);
            }
        }

//        Log.e("---Tag","setPivotY->"+mContentView.getHeight() / 2+"setScaleX ->"+rightScale);

        // 2.菜单的动画    缩放  0.7 - 1.0    alpha  0.6 - 1.0f
        ViewCompat.setTranslationX(mMenuView, l * 0.3f);
        float leftScale = 0.7f + 0.3f * (1 - scale);
        ViewCompat.setScaleX(mMenuView, leftScale);
        ViewCompat.setScaleY(mMenuView, leftScale);
        float leftAlpha = 0.6f + 0.4f * (1 - scale);
        ViewCompat.setAlpha(mMenuView, leftAlpha);
        if (mIsAddShadowView) {
            // 控制阴影 0 - 1
            float alphaScale = 1 - scale;
            mShadowView.setAlpha(alphaScale);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (mIsIntercept) {
            return true;
        }
        // 拦截处理事件
        if (mGestureDetector.onTouchEvent(ev)) {
            return mGestureDetector.onTouchEvent(ev);
        }


        switch (ev.getAction()) {
            // TODO 快速滑动处理
            // 怎样才算快速滑动   手指按下 和抬起  时间 距离  手势处理类
            case MotionEvent.ACTION_UP:
                int currentScrollX = getScrollX();
                if (currentScrollX < mMenuWidth / 2) {
                    // 打开菜单
                    openMenu();
                } else {
                    // 关闭菜单
                    closeMenu();
                }
                return true;
        }
        return super.onTouchEvent(ev);
    }
    /**
     * 关闭菜单
     */
    private void closeMenu() {
        smoothScrollTo(mMenuWidth, 0);
        mIsOpenMenu = false;
    }

    /**
     * 打开菜单
     */
    private void openMenu() {
        smoothScrollTo(0, 0);
        mIsOpenMenu = true;

    }
    class GestureDetectorListener extends GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            //只关注 快速滑动
            //打开时往右边快速滑动 关闭的时候往左边快速滑动
            if (mIsOpenMenu) {
                //打开时往右边快速滑动(关闭)
                if (velocityX < 0 && velocityX > velocityY) {
                    closeMenu();
                    return true;
                }

            } else {
                // 关闭的时候往左边快速滑动（打开）
                if (velocityX > 0 && velocityX > velocityY) {
                    openMenu();
                    return true;
                }
            }

            return super.onFling(e1, e2, velocityX, velocityY);
        }
    }

}
